package com.corner.presenter.imp;

import android.database.Cursor;

import com.corner.R;
import com.corner.app.App;

import com.corner.model.db.DBConstans;
import com.corner.model.db.Session;
import com.corner.model.db.SessionDao;
import com.corner.model.db.User;
import com.corner.presenter.ISelectContactPresenter;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.view.ISelectContactView;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2015/7/22，00.16.
 * 描述：
 */
public class SelectContactPresenter extends BasePresenter<ISelectContactView> implements ISelectContactPresenter {
    @Override
    public void requestUsers() {
        Observable.create(new Observable.OnSubscribe<List<User>>() {
            @Override
            public void call(Subscriber<? super List<User>> subscriber) {
                Cursor cursor = App.application.daoSession.getSessionDao().getDatabase()
                        .query(App.application.daoSession.getSessionDao().getTablename(),null,
                                SessionDao.Properties.Type.columnName + " != ? ",
                                new String[]{DBConstans.LIKE},
                                SessionDao.Properties.SessionName.columnName, null,
                                SessionDao.Properties.Timestamp.columnName + " desc ");
                List<Session> sessions = App.application.daoSession.getSessionDao().cursorToList(cursor);
                List<User> users = new ArrayList<User>();
                for (Session session : sessions) {
                    User user = App.application.daoSession.getUserDao().load(Long.valueOf(session.getSessionName()));
                    if (user != null) {
                        users.add(user);
                    }
                }
                subscriber.onNext(users);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<User>>() {
            @Override
            public void call(List<User> users) {
                if (view != null) {
                    view.showContact(users);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                view.showError(App.application.getString(R.string.load_contact_error));
            }
        });
    }
}
